#coding:utf-8
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from homeapp.BLL.tlog_service import tlog_service
from homeapp.BLL.tnote_service import tnote_service
from homeapp.BLL.rtlog_tnote_service import rtlog_tnote_service
# from homeapp.BLL.tnote_service import tnote_service
from homeapp.models import TLog
from homeapp.models import TNote

class log:

    @staticmethod
    def detail(request):
        guid = request.GET.get("guid")
        mytitle = request.GET.get("mytitle")
        # item = tlog_service.selectbyguid
        # 从日志的guid得到一个记述的guids
        # select homeapp_rtlog_tnote.guid, homeapp_rtlog_tnote.guid rguid, Log_Guid , Note_Guid , `order`, homeapp_tnote.guid , homeapp_tnote.guid tguid, Account_Guid , NoteDateTime , Path , Text , NoteType_Guid  from homeapp_rtlog_tnote join homeapp_tnote on homeapp_rtlog_tnote.Note_Guid = homeapp_tnote.guid where homeapp_rtlog_tnote.Log_Guid <> '';
        # select homeapp_rtlog_tnote.guid, homeapp_rtlog_tnote.guid rguid, Log_Guid , Note_Guid , `order`, homeapp_tnote.guid , homeapp_tnote.guid tguid, Account_Guid , NoteDateTime , Path , Text , NoteType_Guid  from homeapp_rtlog_tnote join homeapp_tnote on homeapp_rtlog_tnote.Note_Guid = homeapp_tnote.guid where homeapp_rtlog_tnote.Log_Guid <> '';

        # 通过指定的Log_Guid， 得到连接表对象
        relmodels = rtlog_tnote_service.selectjoinmodelbyLogId(guid)

        # 通过得到的连接 表对象，得到一个guid列表
        guids = []
        for myguid in relmodels:
            guids.append(myguid.tguid)

        # items = tlog_service.selectbyguids(guids)
        items = tlog_service.selectbyguids(guids)

        obj = {
            "viewmodel":{
                "items":items,
                "mytitle":str(mytitle),
                # "mytitle":mytitle,
            }
        }

        return render(request, "homeapp/log_detail.html", obj)

    @staticmethod
    def index(request):

        # 显示index页面
        # return HttpResponse("hello, world")

        items = tlog_service.selectlog()

        obj = {
            "viewmodel":{
                "items":items
            }
        }

        return render(request, "homeapp/log_index.html", obj)

    @staticmethod
    def add(request):

        # 查询数据库
        # 可能还需要，因为在详情的页面中也需要这个方法
        guids = request.POST.getlist('guids', [])

        # items = tlog_service.selectbyguids(guids)
        items = tlog_service.selectbyguids(guids)

        obj = {
            "viewmodel":{
                "items":items
            }
        }
        return render(request, "homeapp/log_add.html", obj)
        # return HttpResponse(items)

    @staticmethod
    def add_post(request):

        # 得到guid列表
        guids = request.POST.getlist('guids', [])

        # 得到标题
        title = request.POST.get("logtitle")

        # 标题和guid列表传入业务逻辑函数
        tlog_service.processnewlog(title, guids)

        # 处理业务逻辑 增加新的日志
        return HttpResponseRedirect("/homeapp/log/index")

